package com.kaibes.platform.file.client.admin;

import java.nio.charset.Charset;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.core.base.annotation.Description;
import com.kaibes.core.base.util.StringUtils;
import com.kaibes.platform.file.client.db.FileMap;
import com.kaibes.platform.file.client.db.FileMapService;
import com.kaibes.platform.file.client.db.FileServer;
import com.kaibes.platform.file.client.db.FileServerService;
import com.kaibes.web.admin.AdminController;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.util.ControllerUtils;

@AdminController
@RequestMapping("/admin/file")
public class FileClientController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private FileMapService fileMapService;
    @Autowired
    private FileServerService fileServerService;
    
    @ApiLink("文件服务端设置")
    @GetMapping("/server")
    public String fileClientSetting(Model model) {
    	List<FileServer> serverList = fileServerService.list();
        model.addAttribute("serverList", serverList);
        return "file-server";
    }

    @ApiLink("文件映射管理")
    @GetMapping("/map")
    public String fileClientManage(Model model, 
    		@RequestParam(defaultValue = "25") @Description("每页长度") int size,
            @RequestParam(defaultValue = "1") @Description("当前页数") int page,
            @RequestParam(defaultValue = "") @Description("搜索内容") String search,
            @RequestParam(required = false) @Description("用户ID") Integer userId,
            @RequestParam(required = false) @Description("文件类型") String type) {
        search = search.trim();
        if (!search.isEmpty()) {
            model.addAttribute("mapPage", fileMapService.pageByUuidLikeOrNameLike(page, size, search));
        } else if (type != null) {
            model.addAttribute("mapPage", fileMapService.pageByType(page, size, type));
        } else if (userId != null) {
            model.addAttribute("mapPage", fileMapService.pageByUserId(page, size, userId));
        } else {
            model.addAttribute("mapPage", fileMapService.page(page, size));
        }
        return "file-map";
    }

    @ApiLink(value = "个人文件管理", validated = false)
    @GetMapping("/map/self")
    public String fileUserManage(@RequestAttribute Integer userId, Model model,
            @RequestParam(defaultValue = "25") @Description("每页长度") int size,
            @RequestParam(defaultValue = "1") @Description("当前页数") int page,
            @RequestParam(defaultValue = "") @Description("搜索内容") String search,
            @RequestParam(required = false) @Description("文件类型") String type) {
        search = search.trim();
        if (!search.isEmpty()) {
            model.addAttribute("mapPage", fileMapService.pageByUserIdAndUuidLikeOrNameLike(page, size, userId, search));
        } else if (type != null) {
            model.addAttribute("mapPage", fileMapService.pageByUserIdAndType(page, size, userId, type));
        } else {
            model.addAttribute("mapPage", fileMapService.pageByUserId(page, size, userId));
        }
        return "file-self";
    }
    
    @ApiLink(value = "查看图片", validated = false)
    @GetMapping("/image/{uuid}")
    public String view(Model model, @PathVariable @Description("文件的UUID") String uuid, 
            @RequestParam(required = false, defaultValue = "0") int page) {
        return viewUuid(model, uuid, page);
    }
    
    @ApiLink(value = "查看图片", validated = false)
    @GetMapping("/image/{uuid}/{page}")
    public String view2(Model model, @PathVariable @Description("文件的UUID") String uuid, 
            @PathVariable int page) {
        return view(model, uuid, page);
    }
    
    @ApiLink(value = "查看文件", validated = false)
    @GetMapping("/view/{uuid}")
    public String viewUuid(Model model, @PathVariable @Description("文件的UUID") String uuid, @RequestParam(required = false, defaultValue = "0") int page) {
    	uuid = StringUtils.removeSuffix(uuid);
    	FileMap mark = fileMapService.getByUuid(uuid);
    	if (mark == null) {
    		return ControllerUtils.REDIRECT_404;
    	}
    	FileServer serverInfo = fileServerService.getById(mark.getServerId());
    	String url = serverInfo.getHost()+"/encrypts/files/"+uuid+mark.getSuffix();
    	if (mark.getType().startsWith("text")) {
    		HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            try {
            	ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
            	byte[] body = entity.getBody();
            	model.addAttribute("content", StringUtils.getString(body, Charset.forName("GBK")));
            } catch (Exception e) {
            }
        	return "file-text";
    	} else if (mark.getType().startsWith("video")) {
    		model.addAttribute("url", url);
        	return "file-video";
    	} else if (mark.getType().startsWith("image")) {
            model.addAttribute("url", url);
            model.addAttribute("title", "浏览图片");
        	return "file-image";
    	} else if (mark.getType().startsWith("application")) {
    		ResponseEntity<String> responseEntity = restTemplate.getForEntity(serverInfo.getHost() + "/encrypts/files/list/{1}", String.class, uuid);
            String result = responseEntity.getBody();
            int length = 0;
            if (result != null) {
                try {
                    length = objectMapper.readTree(result).get("length").intValue();
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
            model.addAttribute("length", length);
            model.addAttribute("page", page);
            model.addAttribute("url", serverInfo.getHost() + "/encrypts/files/"+uuid);
            model.addAttribute("title", "浏览图片");
        	return "file-images";
    	}
    	return ControllerUtils.FORWARD_404;
    }
    
    @ApiLink(value = "查看文件", validated = false)
    @GetMapping("/view/{uuid}/{page}")
    public String viewPage(Model model, @PathVariable @Description("文件的UUID") String uuid, 
            @PathVariable int page) {
        return viewUuid(model, uuid, page);
    }
    
}
